package mundo;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.MalformedURLException;
import java.net.MulticastSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Observable;
import java.util.Observer;

import commons.IAplicacionLocal;

import sun.misc.ClassLoaderUtil;

public class ThreadServirAplicacion extends Observable implements Runnable
{
	private IAplicacionLocal aplicacion;
	private P2P p2p;
	
	public ThreadServirAplicacion( IAplicacionLocal ap, P2P pdp )
	{
		aplicacion = ap;
		p2p = pdp;
	}
	
	public void run( )
	{
		Socket socket = null;
		PrintWriter out = null;
		BufferedReader in = null;
		ServerSocket receptor;
		
		while( true )
		{
			try {
				receptor = new ServerSocket( aplicacion.darPuerto( ) );
				break;
			} catch (IOException e2) {
				
			}
		}
		
		while( p2p.darListaLocales().contains( aplicacion ) )
		{
			try 
			{
				socket = receptor.accept( );
				out = new PrintWriter( socket.getOutputStream( ), true );
				in = new BufferedReader( new InputStreamReader( socket.getInputStream( ) ) );
				
				String mensaje = in.readLine();
				String[] args = mensaje.split( P2P.SEPARADOR );
				
				String resultado = aplicacion.usarAplicacion( args );
				
				out.println( resultado );
				
				out.close();
				in.close();
				socket.close();
			} 
			catch (IOException e) 
			{
				System.out.println( e.getMessage() );
				try {
					in.close();
					out.close();
					socket.close();
				} catch (IOException e1) {
					
				}
			}
		}
		p2p.setCambiado();
	}
	
}
